package com.framework.utils.pay.suixingfu;

import com.framework.exception.RRException;
import com.framework.utils.httpClient.HttpClientUtil;
import com.framework.utils.json.JsonUtils;
import com.framework.utils.pay.suixingfu.horfu.entity.DF1003Request;
import com.framework.utils.pay.suixingfu.horfu.entity.DF1003Response;
import com.framework.utils.pay.suixingfu.horfu.entity.DF1004Response;
import com.framework.utils.pay.suixingfu.horfu.entity.RequestMessage;
import com.framework.utils.pay.suixingfu.horfu.util.BankCodeUtils;
import com.framework.utils.pay.suixingfu.horfu.util.Base64Utils;
import com.framework.utils.pay.suixingfu.horfu.util.DESUtils;
import com.framework.utils.pay.suixingfu.horfu.util.RSAUtils;
import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SuiXingFuPay {
	private static final String PAY = "/pay.do";
	
	private static String PAY_RESULT = "/queryPayResult.do";
	
	private static final String TRANCD = "DF1003";
	
	public static void main(String[] args) {
		suiXingFuPay("1", "201800134343435326548", "程康", "232342", "232323", "农业银行", "13357705236", "102312505050","","","");
	}
	

	/**
	 *
	 * @param trans_amt 提现金额
	 * @param payItemId 唯一编号
	 * @param acct_name 收款人户名
	 * @param acct_no 收款人卡号
	 * @param bnkCd 银行编码
	 * @param bnkNm 银行名称
	 * @param phone  手机号码
	 * @param lineNo 银行行号
	 */
	public static void suiXingFuPay(String trans_amt,String payItemId,String acct_name,String acct_no,String bnkCd,String bnkNm,String phone,String lineNo,String publicKey,String privateKey,String clientId){
		DF1003Request df3 = new DF1003Request();
		df3.setPayTyp(BankCodeUtils.payTyp_01);
		//总金额
		df3.setTotalPayAmt(trans_amt);
		//笔数
		df3.setTotalPayCount("1");
		List<DF1003Request.PayItems> piList = new ArrayList<DF1003Request.PayItems>();
		DF1003Request.PayItems pi = new DF1003Request.PayItems();
		pi.setPayItemId(payItemId); 
		pi.setSeqNo("1");
		//交易金额
		pi.setPayAmt(trans_amt);
		//收款人户名
		pi.setActNm(acct_name);
		//收款人卡号
		pi.setActNo(acct_no);
		//00：对公  01：对私
		pi.setActTyp("00");
		//银行编号
		pi.setBnkCd(bnkCd);
		//银行名称
		pi.setBnkNm(bnkNm);
		//银行行号
		pi.setLbnkNo(lineNo);
		pi.setLbnkNm(""); 
		pi.setRmk("");
		//是否短信提醒
		pi.setSmsFlg("1");
		//手机号码
		pi.setTel(phone);
		//付款用途
		pi.setBankPayPurpose("提现");
		piList.add(pi);
		df3.setPayItems(piList);
		String json = JsonUtils.toJson(df3);
		Map<String, Object> map = queryPayResult(json, payItemId, publicKey, privateKey, clientId);
		System.out.println("提现返回结果======================"+map);
		String resCode = map.get("resCode").toString();
		if(!StringUtils.isEmpty(resCode) && "0000".equals(resCode)){
			System.out.print("提现成功====================");
		}else{
			String resMsg = map.get("resMsg").toString();
				try {
					throw new RRException("9000",URLDecoder.decode(resMsg+"("+resCode+")","utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
		}
	}

	/**
	 *  根据订单查询
	 * @param json
	 * @param reqId
	 * @param publicKey
	 * @param privateKey
	 * @param clientId
	 * @return
	 */
	public static Map<String, Object> queryPayResult(String json,String reqId,String publicKey,String privateKey,String clientId) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		RequestMessage rm = new RequestMessage();
		//商家编号
		rm.setClientId(clientId);
		rm.setReqId(reqId);
		//交易码
		rm.setTranCd(TRANCD);
		//版本
		rm.setVersion(BankCodeUtils.version);
		if(json==null || "".equals(json)){
			resMap.put("resCode","0001");
	        resMap.put("resMsg", "json为空");
	        resMap.put("msg", "0001,json为空");
			return resMap;
		}
		try{
			byte[] bs = DESUtils.encrypt(json.getBytes(StandardCharsets.UTF_8), "12345678");
			//Base64编码
			String reqDataEncrypt = Base64Utils.encode(bs);
			rm.setReqData(reqDataEncrypt);
			String priKey = privateKey;
			System.out.println(priKey);
			//RSA签名
			rm.setSign(RSAUtils.sign(reqDataEncrypt, priKey));
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("resCode","0002");
	        resMap.put("resMsg", "加密参数出现异常");
	        resMap.put("msg", "0002,加密参数出现异常");
			return resMap;
		}
		try{
			String reqStr = JsonUtils.toJson(rm);
			System.out.print("请求参数===============");
			System.out.print(reqStr);
			String url = BankCodeUtils.agentPayUrl;
			String body = "";
			try {
				 body = HttpClientUtil.doPost(url+PAY,reqStr);
				System.out.print("请求地址===============");
				System.out.print(url+PAY);
				System.out.print("返回body===============");
				System.out.print(body);
			} catch (Exception e) {
				resMap.put("resCode","0001");
		        resMap.put("resMsg", "系统错误！"+body);
				return resMap;
			}
			if(body==null || "".equals(body) || "exception".equals(body)){
				resMap.put("resCode","0002");
		        resMap.put("resMsg", "请求上游出现异常："+body);
				return resMap;
			}
			RequestMessage requestMessage = JsonUtils.fromJson(body,RequestMessage.class);
			String resData = requestMessage.getResData();
			byte[] base64bs = Base64Utils.decode(resData);
			// DES解密
			byte[] debs = DESUtils.decrypt(base64bs, "12345678");
			String resDataDecrypt = new String(debs, StandardCharsets.UTF_8);
			if(!"000000".equals(requestMessage.getResCode())){
				resMap.put("resCode",requestMessage.getResCode());
		        resMap.put("resMsg", requestMessage.getResMsg());
		        resMap.put("msg", requestMessage.getResCode()+requestMessage.getResMsg());
		        return resMap;
			}
			DF1003Response dr3 = JsonUtils.fromJson(resDataDecrypt, DF1003Response.class);
			resMap.put("resCode","0000");
	        resMap.put("dr3", dr3);
	        requestMessage.setResData(resDataDecrypt);
			String msg=JsonUtils.toJson(requestMessage);
			resMap.put("msg",msg);
			return resMap;
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("resCode","0002");
	        resMap.put("resMsg", "请求接口出现异常:"+e.getMessage());
			return resMap;
		}
	}
	
	public  Map<String,Object> toQueryAgentPayment(String json,String reqId,String publicKey,String privateKey,String clientId){
		Map<String, Object> resMap = new HashMap<String, Object>();
		RequestMessage rm = new RequestMessage();
		rm.setClientId(clientId);
		rm.setReqId(reqId);
		rm.setTranCd(TRANCD);
		rm.setVersion(BankCodeUtils.version);
		if(json==null || "".equals(json)){
			resMap.put("resCode","0001");
	        resMap.put("resMsg", "json为空");
	        resMap.put("msg", "0001,json为空");
	        resMap.put("msg", "0001,json为空");
			return resMap;
		}
		try{
			byte[] bs = DESUtils.encrypt(json.getBytes(StandardCharsets.UTF_8), "12345678");
			//Base64编码
			String reqDataEncrypt = Base64Utils.encode(bs);
			
			System.out.println("Base64编码："+reqDataEncrypt);
			
			rm.setReqData(reqDataEncrypt);
			String priKey = privateKey;
			//RSA签名
			rm.setSign(RSAUtils.sign(reqDataEncrypt, priKey));
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("resCode","0002");
	        resMap.put("resMsg", "加密参数出现异常");
	        resMap.put("msg", "0002,加密参数出现异常");
			return resMap;
		}
		String reqStr=JsonUtils.toJson(rm);
		String url = BankCodeUtils.agentPayUrl;
		String body=HttpClientUtil.doPost(url+PAY_RESULT,reqStr);
		RequestMessage requestMessage = JsonUtils.fromJson(body,RequestMessage.class);
		String resData = requestMessage.getResData();
		try{
			byte[] base64bs = Base64Utils.decode(resData);
			// DES解密
			byte[] debs = DESUtils.decrypt(base64bs, "12345678");
			
			String resDataDecrypt = new String(debs, StandardCharsets.UTF_8);
			if(!"000000".equals(requestMessage.getResCode())){
				resMap.put("resCode",requestMessage.getResCode());
		        resMap.put("resMsg", requestMessage.getResMsg());
		        resMap.put("msg", requestMessage.getResCode()+requestMessage.getResMsg());
		        return resMap;
			}
			DF1004Response dr4 = JsonUtils.fromJson(resDataDecrypt, DF1004Response.class);
			resMap.put("resCode","0000");
	        resMap.put("dr4", dr4);
	        requestMessage.setResData(resDataDecrypt);
			String msg=JsonUtils.toJson(requestMessage);
			resMap.put("msg",msg);
			System.out.println(msg);
			return resMap;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

}
